<?php
/**
 * Description of jlojaloader
 *
 * @author João Neto
 */
require_once JPATH_COMPONENT_ADMINISTRATOR . DS . '_lib' . DS . 'exception' . DS . 'modelnotfound.php';

class JLoja_Loader
{
	private $_modelSuffix;
	private $_jlojaPrefix = 'Jloja';
	public function __construct()
	{
		$app =JFactory::getApplication();
		$this->_modelSuffix = $this->classify( $app->getCfg('dbprefix') ) . $this->_jlojaPrefix;
	}

	public function loadModel( $class )
	{
		$className = $this->_modelSuffix . $class;
		return new $className();

	}
	
	/**
	 * Get the Doctrine_Table object for the passed model
	 *
	 * @param string $componentName
	 * @return Doctrine_Table
	 */
	public function loadTable( $class )
	{
		$className = $this->_modelSuffix . $class;
		return Doctrine::getTable( $className );

	}
	/**
	 * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName'
	 *
	 * @param string  $word  Word to classify
	 * @return string $word  Classified word
	 */
	public static function classify($word)
	{
		$word = preg_replace('/[$]/', '', str_replace( '_', '', $word ) );
		return preg_replace_callback('~(_?)(_)([\w])~', array("JLoja_Loader", "classifyCallback"), ucfirst(strtolower($word)));
	}

	/**
	 * Callback function to classify a classname properly.
	 *
	 * @param  array  $matches  An array of matches from a pcre_replace call
	 * @return string $string   A string with matches 1 and mathces 3 in upper case.
	 */
	public static function classifyCallback($matches)
	{
		return $matches[1] . strtoupper($matches[3]);
	}
}